#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

int ticket = 1000;

namespace wjl
{
    class Mutex
    {
    public:
        Mutex()
        {
            pthread_mutex_init(&_lock, nullptr);
        }

        void Lock()
        {
            pthread_mutex_lock(&_lock);
        }

        void UnLock()
        {
            pthread_mutex_unlock(&_lock);
        }

        ~Mutex()
        {
            pthread_mutex_destroy(&_lock);
        }

    private:
        pthread_mutex_t _lock;
    };
}

using namespace wjl;

class LockManager
{
public:
    LockManager(Mutex &mutex)
        : _mutex(mutex)
    {
        _mutex.Lock();
    }

    ~LockManager()
    {
        _mutex.UnLock();
    }

private:
    Mutex& _mutex;//所只有一把，所以这里需要使用别名，否则不能满足使用所来保护原子性
};

Mutex mutex;

void *thread_function(void *arg)
{
    std::string name = (char *)arg;
    LockManager lock_manager(mutex);
    while (1)
    {
        if (ticket > 0)
        {
            usleep(1000);
            std::cout << "我是子线程：" << name << "票还剩" << ticket << std::endl;
            ticket--;
        }
        else
        {
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t t1;
    pthread_t t2;
    pthread_t t3;
    pthread_t t4;

    pthread_create(&t1, nullptr, thread_function, (void *)"thread-1");
    pthread_create(&t2, nullptr, thread_function, (void *)"thread-2");
    pthread_create(&t3, nullptr, thread_function, (void *)"thread-3");
    pthread_create(&t4, nullptr, thread_function, (void *)"thread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
    return 0;
}
